package com.aviation.sell_ticket.tool;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    RedissonClient redisson;//引入分布式锁

    /**
     * 对多个进行加锁
     * @param locks 锁
     * @return  RLock
     */
    public RLock getMultiLock(RLock... locks){
        return redisson.getMultiLock(locks);
    }

    /**
     * 写入数据设置过期时间
     */
    public void setRidesTime(String key, String value, Long time, TimeUnit timeType) {
        redisTemplate.opsForValue().set(key, value, time, timeType);
    }

    /**
     * 验证key是否存在
     *
     * @param key 键值
     * @return Boolean
     */
    public Boolean isSetRedis(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 提取key值
     *
     * @param key 键
     * @return String
     */
    public String getRedis(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除单个key
     * @param key 键
     * @return Boolean
     */
    public Boolean deleteRedis(String key) {
        return redisTemplate.delete(key);
    }


    /**
     * 批量删除
     * @param keys 多个key
     */
    public void deleteRedisList(List<String> keys) {
        for (String key : keys) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 提取多个key
     * @param key 键
     * @return Set<String>
     */
    public Set<String> getKeys(String key){
        return redisTemplate.keys(key);
    }


}

